package com.coocaa.ops.admin.v1.captcha;

import cloud.tianai.captcha.common.constant.CaptchaTypeConstant;
import cloud.tianai.captcha.spring.application.ImageCaptchaApplication;
import cloud.tianai.captcha.spring.vo.CaptchaResponse;
import cloud.tianai.captcha.spring.vo.ImageCaptchaVO;
import cloud.tianai.captcha.validator.common.model.dto.ImageCaptchaTrack;
import com.coocaa.ops.common.core.base.model.R;
import com.coocaa.ops.common.tool.json.JsonUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * @author bijiahao
 * @date : 2023/8/14 15:17
 * @description
 */
@RestController
public class CaptchaController {
    @Autowired
    private ImageCaptchaApplication imageCaptchaApplication;

    @RequestMapping("/gen")
    public R genCaptcha(HttpServletRequest request, @RequestParam(value = "type", required = false) String type) {
        if (StringUtils.isBlank(type)) {
            type = CaptchaTypeConstant.SLIDER;
        }
        CaptchaResponse<ImageCaptchaVO> response = imageCaptchaApplication.generateCaptcha(type);
        return R.ok().data(response);
    }

    @RequestMapping("/check")
    public R checkCaptcha(@RequestParam("id") String id,
                          @RequestParam("jsonStr") String jsonStr,
                          HttpServletRequest request) {
        ImageCaptchaTrack imageCaptchaTrack = (ImageCaptchaTrack) JsonUtil.json2Object(jsonStr, ImageCaptchaTrack.class);
        boolean isOk = imageCaptchaApplication.matching(id, imageCaptchaTrack).isSuccess();
        if (isOk) {
            return R.ok();
        }
        return R.fail("验证码错误");
    }

}
